<template>
  <div :class="{'mobile-table mobile-pt mobile-min-height':showMobilePage}" class="mengli-all-order min-fill-page">
    <dataDisplay
      v-loading="statisticsLoading"
      :data-list="displayData"
      class="mobile-data"
      style="margin-bottom:16px;"
    />
    <div v-if="!showMobilePage" style="position:relative;margin-bottom:16px;">
      <FilterTool
        ref="FilterToolRef"
        v-model="paramsObj"
        :filter-list="filterList"
        show-search-btn
        is-show-config
        @handelClick="queryClick"
        @queryEmpty="queryEmpty"
        @filterTagStatus="filterTagStatus"
      />
      <div class="opeator-bar">
        <el-dropdown
          v-if="canCreate"
          trigger="click">
          <div>
            <createBtn/>
          </div>
          <el-dropdown-menu slot="dropdown" style="padding:0;">
            <el-dropdown-item
              v-if="hasRouteAuth('mengli:iPOrder:create')"
              style="width:96px;padding:0;text-align:center;"
              @click.native="toCreate(0)">
              <div>商务订单</div>
            </el-dropdown-item>
            <!-- <el-dropdown-item
              v-if="hasRouteAuth('mengli:emojiOrder:create')"
              style="width:96px;padding:0;text-align:center;"
              @click.native="toCreate(1)">
              <div>营销授权</div>
            </el-dropdown-item> -->
            <el-dropdown-item
              v-if="hasRouteAuth('mengli:commerceOrder:create')"
              style="width:96px;padding:0;text-align:center;"
              @click.native="toCreate(2)">
              <div>电商销售</div>
            </el-dropdown-item>
            <!-- <el-dropdown-item
              v-if="hasRouteAuth('mengli:channelOrder:create')"
              style="width:96px;padding:0;text-align:center;"
              @click.native="toCreate(3)">
              <div>渠道订单</div>
            </el-dropdown-item> -->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div v-loading="listLoading" class="table-list" style="min-height: 300px;">
      <u-table
        v-if="list.items.length"
        ref="allOrderTableRef"
        :data="list.items"
        :height="setTableHeight"
        :row-height="rowHeight()"
        :border="true"
        beautify-table
        header-drag-style
        use-virtual
        class="fb-table"
        element-loading-text="加载中..."
        empty-text="暂无数据"
        header-cell-class-name="order-data-header-cell"
        fit
        hightlight-current-row
        @sort-change="sortMethod">
        <u-table-column align="left" label="订单类型" width="120">
          <template slot-scope="scope">
            <div>{{ scope.row.orderType | mengliOrderStatus }}</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="订单编号" min-width="220">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.orderNum" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.orderNum }}</div>
              <div class="ellipsis" style="cursor:pointer;color: #406EFF;" @click="toCheck(scope.row)">{{ scope.row.orderNum }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="right" label="收入(元)" width="120" sortable="custom" prop="income_amount">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.income" :price="scope.row.income / 100" />
          </template>
        </u-table-column>
        <u-table-column align="right" label="成本(元)" width="120" sortable="custom" prop="cost">
          <template slot-scope="scope">
            <PriceColumn :real-val="scope.row.cost" :price="scope.row.cost / 100" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="客户名称" min-width="220">
          <template slot-scope="scope">
            <ToolTip :content="scope.row.clientName" />
          </template>
        </u-table-column>
        <u-table-column align="left" label="销售" min-width="80">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.market" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.market }}</div>
              <div class="ellipsis">{{ scope.row.market }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="IP形象" width="200">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.ipInfo" class="item" placement="top" effect="dark">
              <div slot="content" style="max-width: 200px;">{{ scope.row.ipInfo }}</div>
              <div class="ellipsis">{{ scope.row.ipInfo }}</div>
            </el-tooltip>
            <div v-else>--</div>
          </template>
        </u-table-column>
        <u-table-column align="left" label="下单日期" min-width="110" sortable="custom" prop="order_create_date">
          <template slot-scope="scope">
            <div v-if="scope.row.orderTime">{{ scope.row.orderTime | standardFormat('YYYY/MM/DD') }}</div>
            <span v-else>--</span>
          </template>
        </u-table-column>
        <u-table-column :width="110" align="left" label="操作" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="toCheck(scope.row)"><span style="font-size:14px;">查看</span></el-button>
            <el-dropdown v-if="isEditAuth(scope.row) && scope.row.orderChannel !== '线上' || isDeleteAuth(scope.row) && scope.row.orderChannel !== '线上'" trigger="click">
              <div class="el-dropdown-link">
                <el-button type="text"><span style="font-size:14px;">更多<i class="el-icon-arrow-down"/></span></el-button>
              </div>
              <el-dropdown-menu slot="dropdown" style="margin-top:-24px;margin-right:15px;padding: 0;">
                <el-dropdown-item v-if="isEditAuth(scope.row) && scope.row.orderChannel !== '线上'" style="width:100px;text-align: center" @click.native="toEdit(scope.row)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="isDeleteAuth(scope.row) && scope.row.orderChannel !== '线上'" style="width:100px;text-align: center" @click.native="toDel(scope.row)">
                  <div>删除</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </u-table-column>
      </u-table>
      <empty-placeholder v-else-if="!list.isInit" style="margin-bottom: 24px" />
    </div>
    <el-row v-if="showMobilePage && list && list.total > 0" type="flex" justify="left">
      <el-pagination
        v-show="list.total > 0"
        :current-page="list.page"
        :page-size="list.perPage"
        :total="list.total"
        :page-sizes="[20, 50, 100, 250, 500]"
        :layout="pageLayout"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-row>
    <fixed-pagination v-show="list.total > 0 && !showMobilePage || showMobilePage">
      <template v-if="showMobilePage">
        <FilterTool
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          show-mobile-icon
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"
        />
        <el-dropdown
          v-if="canCreate"
          style="display: flex;flex:1;"
          trigger="click">
          <createBtn mobile-table />
          <el-dropdown-menu slot="dropdown" style="padding:0;width: calc(100vw - 88px);">
            <el-dropdown-item
              v-if="hasRouteAuth('mengli:iPOrder:create')"
              style="width:100%;padding:0;text-align:center;"
              @click.native="toCreate(0)">
              <div>商务订单</div>
            </el-dropdown-item>
            <el-dropdown-item
              v-if="hasRouteAuth('mengli:commerceOrder:create')"
              style="width:100%;padding:0;text-align:center;"
              @click.native="toCreate(2)">
              <div>电商销售</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
      <template v-if="!showMobilePage">
        <span style="flex:1;"/>
        <el-pagination
          v-show="list.total > 0"
          :current-page="list.page"
          :page-size="list.perPage"
          :total="list.total"
          :page-sizes="[20, 50, 100, 250, 500]"
          layout="total, prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </template>
    </fixed-pagination>
  </div>
</template>
<script>
import FilterTool from '@/components/Tool/filter';
import Title from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import createBtn from '@/components/Common/baseComponent/createBtn';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { getmengliAllOrder, mengliOrderDel, getAllOrderStatistics } from '@/api/mengli';
import { mengliOrderStatus } from '@/filters/status';
import { moneyFilter } from '@/filters/number';
import { standardFormat } from '@/filters/date';
import { hasRouteAuth } from '@/utils/permission';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import TableAdaptive from '@/mixins/tableAdaptive';
import { mapState } from 'vuex';
import icon_6 from '@/assets/dataDisplay/icon_6.png';
import icon_10 from '@/assets/dataDisplay/icon_10.png';
import icon_11 from '@/assets/dataDisplay/icon_11.png';
import rmb from '@/assets/dataDisplay/rmb.png';
import axios from 'axios';
import mobileTable from '@/mixins/mobileTable';

export default {
  components: { FilterTool, Title, EmptyPlaceholder, createBtn, dataDisplay },
  filters: { mengliOrderStatus, moneyFilter, standardFormat },
  mixins: [TableAdaptive, mobileTable],
  data() {
    return {
      paramsObj: {},
      orderTypeOption: [
        { value: 0, label: '商务订单' },
        // { value: 1, label: '营销授权' },
        { value: 2, label: '电商销售' }
        // { value: 3, label: '渠道订单' }
      ],
      page: 1,
      perPage: 20,
      list: {
        items: [],
        page: 1,
        perPage: 20,
        total: 0,
        isInit: true
      },
      sortType: '',
      sortName: '',
      listLoading: false,
      rangeKeyArr: [{
        attr: 'orderTime',
        start: 'orderStartTime',
        end: 'orderEndTime',
        type: 'time'
      }],
      isUmyTable: true,
      statisticsData: {},
      statisticsLoading: false,
      cancelToken: null
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    canCreate() {
      return hasRouteAuth('mengli:iPOrder:create') || hasRouteAuth('mengli:emojiOrder:create') || hasRouteAuth('mengli:commerceOrder:create');
    },
    tableOutsideHeight() {
      return 246;
    },
    filterList() {
      const arr = [
        // 下拉
        { keyword: 'orderType', name: '订单类型', type: 'select', options: this.orderTypeOption },
        // 输入框
        { keyword: 'orderNum', name: '订单编号', type: 'input', labelWidth: '70px' },
        { keyword: 'clientName', name: '客户名称', type: 'input', labelWidth: '70px' },
        { keyword: 'ipFigure', name: 'IP形象', type: 'input', labelWidth: '70px' },
        { keyword: 'ipSeries', name: 'IP系列', type: 'input', labelWidth: '70px' },
        { keyword: 'market', name: '销售', type: 'input', labelWidth: '70px' },
        // 日期
        { keyword: 'orderTime', name: '下单日期', timeType: 'daterange', type: 'rangeDate', labelWidth: '70px' }
      ];
      return arr;
    },
    displayData() {
      const statisticsData = this.statisticsData;
      return [
        { data: statisticsData.orderNum, label: '订单数', icon: icon_6, isMoney: false },
        { data: statisticsData.saleNum / 100, label: '销售额', icon: icon_10 },
        { data: statisticsData.costNum / 100, label: '成本', icon: icon_11 },
        { data: (statisticsData.saleNum - statisticsData.costNum) / 100, label: '毛利', icon: rmb }
      ];
    }
  },
  created() {
    this.fetchData(true);
  },
  methods: {
    hasRouteAuth,
    fetchData(reset = false, isPage = false) {
      if (reset) this.page = 1;
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      // 时间处理
      paramsRangeFormat(this.rangeKeyArr, params);

      params.sortType = this.sortType;
      params.sortName = this.sortName;
      params.page = this.page;
      params.perPage = this.perPage;
      params.notShowNoAuthTip = true;
      this.listLoading = true;
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source();
      this.cancelToken = source;
      getmengliAllOrder(params, source.token).then(({ data }) => {
        if (data.items) {
          data.items.forEach(i => {
            if (i.ipAry) {
              const ip = [];
              i.ipAry.forEach(j => {
                const name = `${j.ipFigure || '--'}/${j.ipSeries || '--'}`;
                ip.push(name);
              });
              i.ipInfo = ip.join(',');
            }
          });
        }
        this.list = data;
        this.list.isInit = false;
        this.listLoading = false;
        this.page = data.page;
        this.perPage = data.perPage;
      }).catch(e => {
        console.error(e);
        this.listLoading = false;
      });
      if (!isPage) {
        this.getAllOrderStatistics(params);
      }
    },
    // 统计面板
    getAllOrderStatistics(params) {
      this.statisticsLoading = true;
      getAllOrderStatistics(params).then(res => {
        if (res.code === 200) {
          this.statisticsData = res.data;
        }
        this.statisticsLoading = false;
      }).catch(e => {
        this.statisticsLoading = false;
      });
    },
    queryClick() {
      this.fetchData(true);
    },
    // 排序
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.fetchData(true, true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData(true, true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData(false, true);
    },
    toCheck(row) {
      this.$router.push({
        name: 'mengliOrderDetail',
        params: { id: row.id },
        query: { type: row.orderType || 0, source: 'all' }
      });
    },
    toEdit(row) {
      this.$router.push({
        name: 'mengliOrderEdit',
        params: { id: row.id },
        query: { type: row.orderType || 0, source: 'all' }
      });
    },
    // 操作
    toCreate(type) {
      this.$router.push({
        name: 'mengliOrderAdd',
        query: { type: type, source: 'all' }
      });
    },
    toDel(row) {
      this.$confirm('是否确定删除该订单', {
        confirmButtonText: '确定',
        type: 'warning',
        showClose: false,
        center: true,
        iconClass: 'charge-icon',
        customClass: 'del-message del-message-cancel'
      }).then(() => {
        mengliOrderDel(row.id).then(res => {
          this.$message.success('删除成功');
          this.fetchData();
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {
        return false;
      });
    },
    // 编辑权限
    isEditAuth(item) {
      const isAdmin = this.userInfo.userName === '管理员';
      const auth = {
        '0': 'mengli:iPOrder:edit',
        '1': 'mengli:emojiOrder:edit',
        '2': 'mengli:commerceOrder:edit',
        '3': 'mengli:channelOrder:edit'
      };
      const orderType = item.orderType || '0';
      return isAdmin || hasRouteAuth(auth[orderType.toString()]);
    },
    isDeleteAuth(item) {
      const isAdmin = this.userInfo.userName === '管理员';
      const auth = {
        '0': 'mengli:iPOrder:delete',
        '1': 'mengli:emojiOrder:delete',
        '2': 'mengli:commerceOrder:delete',
        '3': 'mengli:channelOrder:delete'
      };
      const orderType = item.orderType || '0';
      return isAdmin || hasRouteAuth(auth[orderType.toString()]);
    }
  }
};
</script>
<style lang="scss" scoped>
.opeator-bar {
  position: absolute;
  right: 0;
  top: 0;
  display: flex;
  align-items: center;
}
.mengli-all-order {
  margin: 16px 16px 0 16px;
  background-color: #fff;
  padding: 20px 20px 55px 20px;
  .order-num {
    color: #406EFF;
  }
}
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
</style>
